package com.njbw.tool;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.http.HttpHeaders;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 导出 word 的 util
 */
public class ExportWordUtil {

    private static Configuration configuration = null;

    private static final String SUFFIX = ".doc";

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        // 根据类加载模板
        configuration.setClassForTemplateLoading(ExportWordUtil.class, "/template/word");
    }

    public static void exportWord(Map map, String title, String ftlName) throws Exception {
        // 1.获取模板
        Template template = configuration.getTemplate(ftlName);
        // 2.读模板写文件——必不可少的会涉及到文件流
        File file = null;
        InputStream is = null;
        ServletOutputStream out = null;
        // 3.创建 doc 文件
        file = createDocFile(map, template);
        is = new FileInputStream(file);
        String fileName = title + SUFFIX;
        HttpServletResponse response = SpringContextUtils.getHttpServletResponse();
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/msword");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        out = response.getOutputStream();
        byte[] buff = new byte[512];
        int byteToRead = -1;
        while ((byteToRead = is.read(buff)) != -1) {
            out.write(buff, 0, byteToRead);
        }
        if (null != is) {
            is.close();
        }
        if (null != out) {
            out.close();
        }
        if (null != file) {
            file.delete();
        }
    }

    /**
     * 创建 word
     * @param dataMap 数据 map
     * @param template 模板
     * @return word temp 文件
     * @throws Exception 异常
     */
    private static File createDocFile(Map dataMap, Template template) throws Exception {
        File file = new File("init.doc");
        Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        // 将数据和模板对应渲染起来
        template.process(dataMap, writer);
        writer.close();
        return file;
    }
}
